<?php
namespace app\sell\controller;

use think\Controller;

class Qrcode extends Controller
{
    //检查是否登录
    public function initialize()
    {
        if (!session('sell')) {
            $this->error('请先登录！', url('/sell/login/login'));
        }
    }
    
    public function index()
    {
        $sellid = session('sell.id');

        $list = DB("huabo_sell")->alias('s')
        ->leftJoin("huabo_store st", "st.sell_id=s.sell_id")
        ->leftJoin("store sto", "sto.id=st.sell_id")
        ->leftJoin("qrcode q", "s.qr_id=q.id")
        ->field("q.num,q.status as is_zaiwang,sto.company,s.*")
        ->where(['s.status' => 0,"s.sell_id" => $sellid])
        ->paginate(20);
        
        $this->assign('list', $list);
        return $this->fetch('index');
    }

    //划拨
    public function huabo(){
        $sellid = session('sell.id');
        if($_POST){
            $count = DB("huabo_sell")->where(['sell_id' => $sellid,"status" => 0])->count();
            $num = $_POST['number'];
            $store = DB("store")->find($_POST['store']);
            $str = "";
            if($num > $count){
                $this->error("剩余数量【{$count}】,划拨数量不得超过剩余数量");
            } else {
                //划拨
                $qrlist = DB("huabo_sell")->where(['sell_id' => $sellid,"status" => 0])->limit($num)->select();
                foreach($qrlist as $key => $qr){
                    $str .= $qr['id'].",";
                    //划拨给商户
                    $result = DB("huabo_store")->insert(['qr_id' => $qr['id'],'sell_id' =>$sellid,'store_id' =>$store['id'],'create_time' => time()]);
                    //修改划拨状态
                    DB("huabo_sell")->where(['id' => $qr['id']])->update(['status' => 1]);
                }
                //添加划拨记录
                $result1 = DB("huabo_logs")->insert(['logs' => "商户于".date("Y-m-d H:i:s")."划拨给【".$store['company'] . "】【".count($qrlist)."】个二维码",'qr_ids' =>$str,"store_id" => $store['id'],"sell_id" => $sellid,'update_time' => time()]);
                //
                if($result && $result1){
                    $this->success();
                } else {
                    $this->error();
                }
            }
            
        } else {
            $this->assign("shengyu", DB("huabo_sell")->where(['sell_id' => $sellid,"status" => 0])->count());
            $this->assign("store", DB("store")->where(['is_del' => 0,"sell_id" => $sellid])->select());
            return $this->fetch();
        }
    }
    
}
